#mdStyle()

<a name="Web-ApacheShiroWebSupport"></a>
Apache Shiro Web Support
========================

*   [Configuration](#Web-Configuration)

    *   [`web.xml`](#Web-%7B%7Bweb.xml%7D%7D)

        *   [Shiro 1.2 and later](#Web-Shiro1.2andlater)
    
            *   [Custom `WebEnvironment` Class](#Web-Custom%7B%7BWebEnvironment%7D%7DClass)
            *   [Custom Configuration Locations](#Web-CustomConfigurationLocations)
    
        *   [Shiro 1.1 and earlier](#Web-Shiro1.1andearlier)
        
            *   [Custom Path](#Web-CustomPath)
            *   [Inline Config](#Web-InlineConfig)
    
    *   [Web INI configuration](#Web-WebINIconfiguration)
    
        *   [`[urls]`](#Web-%7B%7B%5Curls%5C%7D%7D)
    
            *   [URL Path Expressions](#Web-URLPathExpressions)
            *   [Filter Chain Definitions](#Web-FilterChainDefinitions)
    
                *   [Available Filters](#Web-AvailableFilters)

*   [Default Filters](#Web-DefaultFilters)
*   [Enabling and Disabling Filters](#Web-EnablingandDisablingFilters)

    *   [General Enabling/Disabling](#Web-GeneralEnabling%2FDisabling)
    *   [Request-specific Enabling/Disabling](#Web-RequestspecificEnabling%2FDisabling)
    *   [Path-specific Enabling/Disabling](#Web-PathspecificEnabling%2FDisabling)

*   [Session Management](#Web-SessionManagement)

    *   [Servlet Container Sessions](#Web-ServletContainerSessions)
    
        *   [Servlet Container Session Timeout](#Web-ServletContainerSessionTimeout)
    
    *   [Native Sessions](#Web-NativeSessions)
    
        *   [`DefaultWebSessionManager`](#Web-%7B%7BDefaultWebSessionManager%7D%7D)
        
            *   [Native Session Timeout](#Web-NativeSessionTimeout)
            *   [Session Cookie](#Web-SessionCookie)
        
                *   [Session Cookie Configuration](#Web-SessionCookieConfiguration)
                *   [Disabling the Session Cookie](#Web-DisablingtheSessionCookie)

*   [Remember Me Services](#Web-RememberMeServices)

    *   [Programmatic Support](#Web-ProgrammaticSupport)
    *   [Form-based Login](#Web-FormbasedLogin)
    *   [Cookie configuration](#Web-Cookieconfiguration)
    *   [Custom `RememberMeManager`](#Web-Custom%7B%7BRememberMeManager%7D%7D)

*   [JSP / GSP Tag Library](#Web-JSP%2FGSPTagLibrary)

    *   [Tag Library Configuration](#Web-TagLibraryConfiguration)
    *   [The `guest` tag](#Web-The%7B%7Bguest%7D%7Dtag)
    *   [The `user` tag](#Web-The%7B%7Buser%7D%7Dtag)
    *   [The `authenticated` tag](#Web-The%7B%7Bauthenticated%7D%7Dtag)
    *   [The `notAuthenticated` tag](#Web-The%7B%7BnotAuthenticated%7D%7Dtag)
    *   [The `principal` tag](#Web-The%7B%7Bprincipal%7D%7Dtag)
    
        *   [Typed principal](#Web-Typedprincipal)
        *   [Principal property](#Web-Principalproperty)

    *   [The `hasRole` tag](#Web-The%7B%7BhasRole%7D%7Dtag)
    *   [The `lacksRole` tag](#Web-The%7B%7BlacksRole%7D%7Dtag)
    *   [The `hasAnyRole` tag](#Web-The%7B%7BhasAnyRole%7D%7Dtag)
    *   [The `hasPermission` tag](#Web-The%7B%7BhasPermission%7D%7Dtag)
    *   [The `lacksPermission` tag](#Web-The%7B%7BlacksPermission%7D%7Dtag)


<a name="Web-configuration"></a>
<a name="Web-Configuration"></a>
Configuration
-------------

The simplest way to integrate Shiro into any web application is to configure a Servlet ContextListener and Filter in web.xml that understands how to read Shiro's INI configuration. The bulk of the INI config format itself is defined in the Configuration pages's [INI Sections](configuration.html#[[#]]#Configuration-INISections) section, but we'll cover some additional web-specific sections here.

#info('Using Spring?', 'Spring Framework users will not perform this setup.  If you use Spring, you will want to read about <a href="spring.html#[[#]]#Spring-WebApplications">Spring-specific web configuration</a> instead.')

<a name="Web-%7B%7Bweb.xml%7D%7D"></a>
#[[###`web.xml`]]#

<a name="Web-Shiro1.2andlater"></a>
#[[####Shiro 1.2 and later]]#

In Shiro 1.2 and later, standard web applications initialize Shiro by adding the following XML chunks to `web.xml`:

``` xml
<listener>
    <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
</listener>

...

<filter>
    <filter-name>ShiroFilter</filter-name>
    <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>ShiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>
```

This assumes a Shiro INI [Configuration](configuration.html "Configuration") file is located at either of the following two locations, using whichever is found first:

1.  `/WEB-INF/shiro.ini`
2.  `shiro.ini` file at the root of the classpath.

Here is what the above config does:

*   The `EnvironmentLoaderListener` initializes a Shiro `WebEnvironment` instance (which contains everything Shiro needs to operate, including the `SecurityManager`) and makes it accessible in the `ServletContext`. If you need to obtain this `WebEnvironment` instance at any time, you can call `WebUtils.getRequiredWebEnvironment(servletContext)`.

*   The `ShiroFilter` will use this `WebEnvironment` to perform all necessary security operations for any filtered request.

*   Finally, the `filter-mapping` definition ensures that all requests are filtered by the `ShiroFilter`, recommended for most web applications to ensure that any request can be secured.

#tip('ShiroFilter filter-mapping', 'It is usually desirable to define the `ShiroFilter filter-mapping` before any other `filter-mapping` declarations to ensure that Shiro can function in those filters as well.')

<a name="Web-Custom%7B%7BWebEnvironment%7D%7DClass"></a>
#[[#####Custom `WebEnvironment` Class]]#

By default the `EnvironmentLoaderListener` will create an `IniWebEnvironment` instance, which assumes Shiro's INI-based [Configuration](configuration.html "Configuration"). If you like, you may specify a custom `WebEnvironment` instance instead by specifying a `ServletContext` `context-param` in `web.xml`:

``` xml
<context-param>
    <param-name>shiroEnvironmentClass</param-name>
    <param-value>com.foo.bar.shiro.MyWebEnvironment</param-value>
</context-param>
```

This allows you to customize how a configuration format is parsed and represented as a `WebEnvironment` instance. You could subclass the existing `IniWebEnvironment` for custom behavior, or support different configuration formats entirely. For example, if someone wanted to configure Shiro in XML instead of INI, they could create an XML-based implementation, e.g. `com.foo.bar.shiro.XmlWebEnvironment`.

<a name="Web-CustomConfigurationLocations"></a>
#[[#####Custom Configuration Locations]]#

The `IniWebEnvironment` class expects to read and load INI configuration files. By default, this class will automatically look in the following two locations for the Shiro `.ini` configuration (in order):

1.  `/WEB-INF/shiro.ini`
2.  `classpath:shiro.ini`

It will use whichever is found first.

However, if you wish to place your config in another location, you may specify that location with another `context-param` in `web.xml`:

``` xml
<context-param>
    <param-name>shiroConfigLocations</param-name>
    <param-value>YOUR_RESOURCE_LOCATION_HERE</param-value>
</context-param>
```

By default, the `param-value` is expected to be resolvable by the rules defined by `ServletContext.`[`getResource`](http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#[[#]]#getResource-java.lang.String-) method. For example, `/WEB-INF/some/path/shiro.ini`

But you may also specify specific file-system, classpath or URL locations by using an appropriate resource prefix supported by Shiro's [ResourceUtils class](static/current/apidocs/org/apache/shiro/io/ResourceUtils.html), for example:

*   `file:/home/foobar/myapp/shiro.ini`
*   `classpath:com/foo/bar/shiro.ini`
*   `url:http://confighost.mycompany.com/myapp/shiro.ini`

<a name="Web-Shiro1.1andearlier"></a>
#[[####Shiro 1.1 and earlier]]#

The simplest way to enable Shiro in a 1.1 or earlier web application is to define the IniShiroFilter and specify a `filter-mapping`:

``` xml
<filter>
    <filter-name>ShiroFilter</filter-name>
    <filter-class>org.apache.shiro.web.servlet.IniShiroFilter</filter-class>
</filter>

...

<!-- Make sure any request you want accessible to Shiro is filtered. /* catches all -->
<!-- requests.  Usually this filter mapping is defined first (before all others) to -->
<!-- ensure that Shiro works in subsequent filters in the filter chain:             -->
<filter-mapping>
    <filter-name>ShiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>
```

This definition expects your INI configuration to be in a shiro.ini file at the root of the classpath (e.g. `classpath:shiro.ini`).

<a name="Web-CustomPath"></a>
#[[#####Custom Path]]#

If you do not want to place your INI config in `/WEB-INF/shiro.ini` or `classpath:shiro.ini`, you may specify a custom resource location as necessary. Add a `configPath init-param` and specify a resource location:

``` xml
<filter>
    <filter-name>ShiroFilter</filter-name>
    <filter-class>org.apache.shiro.web.servlet.IniShiroFilter</filter-class>
    <init-param>
        <param-name>configPath</param-name>
        <param-value>/WEB-INF/anotherFile.ini</param-value>
    </init-param>
</filter>

...
```

Unqualified (schemeless or 'non-prefixed') `configPath` values are assumed to be `ServletContext` resource paths, resolvable via the rules defined by the
`ServletContext.`[`getResource`](http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#[[#]]#getResource-java.lang.String-) method.

#warning('ServletContext resource paths - Shiro 1.2+', 'ServletContext resource paths are available in Shiro 1.2 and later. In 1.1 and earlier, all <code>configPath</code> definitions must specify a <code>classpath:</code>, <code>file:</code> or <code>url:</code> prefix.')

You may also specify other non-`ServletContext` resource locations by using `classpath:`, `url:`, or `file:` prefixes indicating classpath, url, or filesystem locations respectively. For example:

``` xml
...
<init-param>
    <param-name>configPath</param-name>
    <param-value>url:http://configHost/myApp/shiro.ini</param-value>
</init-param>
...
```

<a name="Web-InlineConfig"></a>
#[[#####Inline Config]]#

Finally, it is also possible to embed your INI configuration inline in web.xml without using an INI file at all. You do this by using the `config init-param` instead of `configPath`:

``` xml
<filter>
    <filter-name>ShiroFilter</filter-name>
    <filter-class>org.apache.shiro.web.servlet.IniShiroFilter</filter-class>
    <init-param><param-name>config</param-name><param-value>

    # INI Config Here

    </param-value></init-param>
</filter>
...
```

Inline config is often fine for small or simple applications, but it is usually more convenient to externalize it in a dedicated shiro.ini file for the following reasons:

*   You might edit security configuration a lot and don't want to add revision control 'noise' to the web.xml file
*   You might want to separate security config from the rest of web.xml config
*   Your security configuration might become large and you want to keep web.xml lean and easier to read
*   You have a complex build system where the same shiro config might need to be referenced in multiple places

It is up to you - use what makes sense for your project.

<a name="Web-webini"></a>
<a name="Web-WebINIconfiguration"></a>
#[[###Web INI configuration]]#

In addition to the standard `[main]`, `[users]` and `[roles]` sections already described in the main [Configuration](configuration.html "Configuration") chapter, you can additionally specify a web-specific `[urls]` section in your `shiro.ini` file:

``` ini
# [main], [users] and [roles] above here
...
[urls]
...
```

The `[urls]` section allows you to do something that doesn't exist in any web framework that we've seen yet: the ability to define ad-hoc filter chains for any matching URL path in your application!

This is _far_ more flexible, powerful and concise than how you define filter chains normally in `web.xml`: even if you never used any other feature that Shiro provided and used only this, it alone would make it worth using.

<a name="Web-%7B%7B%5Curls%5C%7D%7D"></a>
#[[####`[urls]`]]#

The format of each line in the `urls` section is as follows:

``` ini
_URL_Ant_Path_Expression_ = _Path_Specific_Filter_Chain_
```

For example:

``` ini
...
[urls]

/index.html = anon
/user/create = anon
/user/** = authc
/admin/** = authc, roles[administrator]
/rest/** = authc, rest
/remoting/rpc/** = authc, perms["remote:invoke"]
```

Next we'll cover exactly what these lines mean.

##### <a name="Web-URLPathExpressions"></a>URL Path Expressions

The token on the left of the equals sign (=) is an [Ant](http://ant.apache.org)-style path expression relative to your web application's context root.

For example, let's say you had the following `[urls]` line:

``` ini
/account/** = ssl, authc
```

This line states that "Any request to my application's path of `/account` or any of it's sub paths (`/account/foo`, `/account/bar/baz`, etc) will trigger the 'ssl, authc' filter chain". We'll cover filter chains below.

Note that all path expressions are relative to your application's context root. This means that if you deploy your application one day to, say, `www.somehost.com/myapp` and then later deploy it to `www.anotherhost.com` (no 'myapp' sub-path), the pattern matching will still work. All paths are relative to the [HttpServletRequest.getContextPath()](http://docs.oracle.com/javaee/1.3/api/javax/servlet/http/HttpServletRequest.html#[[#]]#getContextPath--) value.

#warning('Order Matters!', 'URL path expressions are evaluated against an incoming request in the order they are defined and the <em>FIRST MATCH WINS</em>.  For example, let''s asume that there are the following chain definitions:

<pre><code class="ini">/account/** = ssl, authc
/account/signup = anon
</code></pre>
<p>If an incoming request is intended to reach <code>/account/signup/index.html</code> (accessible by all ''anon''ymous users), <em>it will never be handled!</em>.  The reason is that the <code>/account/**</code> pattern matched the incoming request first and ''short-circuited'' all remaining definitions.</p>
<p>Always remember to define your filter chains based on a <em>FIRST MATCH WINS</em> policy!</p>')

<a name="Web-FilterChainDefinitions"></a>
#[[#####Filter Chain Definitions]]#

The token on the right of the equals sign (=) is comma-delimited list of filters to execute for a request matching that path. It must match the following format:

``` ini
filter1[optional_config1], filter2[optional_config2], ..., filterN[optional_configN]
```

where:

*   _filterN_ is the name of a filter bean defined in the `[main]` section and
*   `[optional_configN]` is an optional bracketed string that has meaning for that particular filter for _that particular path_ (per-filter, _path-specific_ configuration!). If the filter does not need specific config for that URL path, you may discard the brackets so `filterN[]` just becomes `filterN`.

And because filter tokens define chains (aka a List), remember that order matters! Define your comma-delimited list in the order that you want the request to flow through the chain.

Finally, each filter is free to handle the response however it wants if its necessary conditions are not met (e.g. perform a redirect, respond with an HTTP error code, direct rendering, etc). Otherwise it is expected to allow the request to continue through the chain on to the final destination view.

#tip('Tip', 'Being able to react to path specific configuration, i.e. the <code>[optional_configN]</code> part of a filter token, is a unique feature available to Shiro filters.
<p>If you want to create your own <code>javax.servlet.Filter</code> implementation that can also do this, make sure your filter subclasses <a class="external-link" href="static/current/apidocs/org/apache/shiro/web/filter/PathMatchingFilter.html">org.apache.shiro.web.filter.PathMatchingFilter</a></p>')

<a name="Web-AvailableFilters"></a>
#[[######Available Filters]]#

The 'pool' of filters available for use in filter chain definitions are defined in the `[main]` section. The name assigned to them in the main section is the name to use in the filter chain definitions. For example:

``` ini
[main]
...
myFilter = com.company.web.some.FilterImplementation
myFilter.property1 = value1
...

[urls]
...
/some/path/** = myFilter
```

<a name="Web-defaultfilters"></a>
<a name="Web-DefaultFilters"></a>
Default Filters
---------------

When running a web-app, Shiro will create some useful default `Filter` instances and make them available in the `[main]` section automatically. You can configure them in `main` as you would any other bean and reference them in your chain definitions. For example:

``` ini
[main]
...
# Notice how we didn't define the class for the FormAuthenticationFilter ('authc') - it is instantiated and available already:
authc.loginUrl = /login.jsp
...

[urls]
...
# make sure the end-user is authenticated.  If not, redirect to the 'authc.loginUrl' above,
# and after successful authentication, redirect them back to the original account page they
# were trying to view:
/account/** = authc
...
```

The default Filter instances available automatically are defined by the [DefaultFilter enum](static/current/apidocs/org/apache/shiro/web/filter/mgt/DefaultFilter.html) and the enum's `name` field is the name available for configuration. They are:

| Filter Name | Class |
| ----------- | ----- |
| anon | [org.apache.shiro.web.filter.authc.AnonymousFilter](static/current/apidocs/org/apache/shiro/web/filter/authc/AnonymousFilter.html) |
| authc | [org.apache.shiro.web.filter.authc.FormAuthenticationFilter](static/current/apidocs/org/apache/shiro/web/filter/authc/FormAuthenticationFilter.html) |
| authcBasic | [org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter](static/current/apidocs/org/apache/shiro/web/filter/authc/BasicHttpAuthenticationFilter.html) |
| logout | [org.apache.shiro.web.filter.authc.LogoutFilter](static/current/apidocs/org/apache/shiro/web/filter/authc/LogoutFilter.html) |
| noSessionCreation | [org.apache.shiro.web.filter.session.NoSessionCreationFilter](static/current/apidocs/org/apache/shiro/web/filter/session/NoSessionCreationFilter.html) |
| perms | [org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter](static/current/apidocs/org/apache/shiro/web/filter/authz/PermissionsAuthorizationFilter.html) |
| port | [org.apache.shiro.web.filter.authz.PortFilter](static/current/apidocs/org/apache/shiro/web/filter/authz/PortFilter.html) |
| rest| [org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter](static/current/apidocs/org/apache/shiro/web/filter/authz/HttpMethodPermissionFilter.html) |
| roles |[org.apache.shiro.web.filter.authz.RolesAuthorizationFilter](static/current/apidocs/org/apache/shiro/web/filter/authz/RolesAuthorizationFilter.html) |
| ssl | [org.apache.shiro.web.filter.authz.SslFilter](static/current/apidocs/org/apache/shiro/web/filter/authz/SslFilter.html) |
| user | [org.apache.shiro.web.filter.authc.UserFilter](static/current/apidocs/org/apache/shiro/web/filter/authc/UserFilter.html) |

<a name="Web-EnablingandDisablingFilters"></a>
Enabling and Disabling Filters
------------------------------

As is the case with any filter chain definition mechanism (`web.xml`, Shiro's INI, etc), you enable a filter just by including it in the filter chain definition, and you disable it by removing it from the chain definition.

But a new feature added in Shiro 1.2 is the ability to enable or disable filters without removing them from the filter chain. If enabled (the default setting), then a request will be filtered as expected. If disabled, then the filter will allow the request to pass through immediately to the next element in the `FilterChain`. You can trigger a filter's enabled state generally based on a configuration property, or you can even trigger it on a _per request_ basis.

This is a powerful concept because it is often more convenient to enable or disable a filter based on certain requirements than to change the static filter chain definition, which would be permanent and inflexible.

Shiro accomplishes this via its [OncePerRequestFilter](static/current/apidocs/org/apache/shiro/web/servlet/OncePerRequestFilter.html) abstract parent class. All of Shiro's out-of-the-box Filter implementations subclass this one and therefore are able to be enabled or disabled without removing them from the filter chain. You can subclass this class for your own filter implementations if you need this functionality as well*.

*[SHIRO-224](https://issues.apache.org/jira/browse/SHIRO-224) will hopefully enable this feature for any filter, not just those subclassing `OncePerRequestFilter`. If this is important to you, please vote for the issue.

<a name="Web-GeneralEnabling%2FDisabling"></a>
#[[###General Enabling/Disabling]]#

The [OncePerRequestFilter](static/current/apidocs/org/apache/shiro/web/servlet/OncePerRequestFilter.html) (and all of its subclasses) supports enabling/disabling across all requests as well as on a per-request basis.

General enabling or disabling of a filter for all requests is done by setting its `enabled` property to true or false. The default setting is `true` since most filters inherently need to execute if they are configured in a chain.

For example, in shiro.ini:

``` ini
[main]
...
# configure Shiro's default 'ssl' filter to be disabled while testing:
ssl.enabled = false

[urls]
...
/some/path = ssl, authc
/another/path = ssl, roles[admin]
...
```

This example shows that potentially many URL paths can all require that a request must be secured by an SSL connection. Setting up SSL while in development can be frustrating and time consuming. While in development, you can disable the ssl filter. When deploying to production, you can enable it with one configuration property - something that is much easier than manually changing all of the URL paths or maintaining two Shiro configurations.

<a name="Web-RequestspecificEnabling%2FDisabling"></a>
#[[###Request-specific Enabling/Disabling]]#

`OncePerRequestFilter` actually determines if the filter is enabled or disabled based on its `isEnabled(request, response)` method.

This method defaults to returning the value of the `enabled` property, which is used for generally enabling/disabling all requests as mentioned above. If you wanted to enable or disable a filter based on _request specific_ criteria, you can override the `OncePerRequestFilter` `isEnabled(request,response)` method to perform more specific checks.

<a name="Web-PathspecificEnabling%2FDisabling"></a>
#[[###Path-specific Enabling/Disabling]]#

Shiro's [PathMatchingFilter](static/current/apidocs/org/apache/shiro/web/filter/PathMatchingFilter.html) (a subclass of `OncePerRequestFilter` has the ability to react to configuration based on a _specific path_ being filtered. This means you can enable or disable a filter based on the path and the path-specific configuration in addition to the incoming request and response.

If you need to be able to react to the matching path and the path-specific configuration to determine if a filter is enabled or disabled, instead of overriding `OncePerRequestFilter` `isEnabled(request,response)` method, you would override the `PathMatchingFilter` `isEnabled(request,response,path,pathConfig)` method instead.

<a name="Web-sessionManagement"></a>
<a name="Web-SessionManagement"></a>
Session Management
------------------

<a name="Web-ServletContainerSessions"></a>
#[[###Servlet Container Sessions]]#

In web environments, Shiro's default session manager [`SessionManager`](static/current/apidocs/org/apache/shiro/session/mgt/SessionManager.html) implementation is the [`ServletContainerSessionManager`](static/current/apidocs/org/apache/shiro/web/session/mgt/ServletContainerSessionManager.html). This very simple implementation delegates all session management duties (including session clustering if the servlet container supports it) to the runtime Servlet container. It is essentially a bridge for Shiro's session API to the servlet container and does little else.

A benefit of using this default is that apps that work with existing servlet container session configuration (timeout, any container-specific clustering mechanisms, etc) will work as expected.

A downside of this default is that you are tied to the servlet container's specific session behavior. For example, if you wanted to cluster sessions, but you used Jetty for testing and Tomcat in production, your container-specific configuration (or code) would not be portable.

<a name="Web-ServletContainerSessionTimeout"></a>
#[[####Servlet Container Session Timeout]]#

If using the default servlet container support, you configure session timeout as expected in your web application's `web.xml` file. For example:

``` xml
<session-config>
  <!-- web.xml expects the session timeout in minutes: -->
  <session-timeout>30</session-timeout>
</session-config>
```

<a name="Web-NativeSessions"></a>
#[[###Native Sessions]]#

If you want your session configuration settings and clustering to be portable across servlet containers (e.g. Jetty in testing, but Tomcat or JBoss in production), or you want to control specific session/clustering features, you can enable Shiro's native session management.

The word 'Native' here means that Shiro's own enterprise session management implementation will be used to support all `Subject` and `HttpServletRequest` sessions and bypass the servlet container completely. But rest assured - Shiro implements the relevant parts of the Servlet specification directly so any existing web/http related code works as expected and never needs to 'know' that Shiro is transparently managing sessions.

<a name="Web-%7B%7BDefaultWebSessionManager%7D%7D"></a>
#[[####`DefaultWebSessionManager`]]#

To enable native session management for your web application, you will need to configure a native web-capable session manager to override the default servlet container-based one. You can do that by configuring an instance of [`DefaultWebSessionManager`](static/current/apidocs/org/apache/shiro/web/session/mgt/DefaultWebSessionManager.html) on Shiro's `SecurityManager`. For example, in `shiro.ini`:

**shiro.ini native web session management**

``` ini
[main]
...
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
# configure properties (like session timeout) here if desired

# Use the configured native session manager:
securityManager.sessionManager = $sessionManager
```

Once declared, you can configure the `DefaultWebSessionManager` instance with native session options like session timeout and clustering configuration as described in the [Session Management](session-management.html "Session Management") section.

<a name="Web-NativeSessionTimeout"></a>
#[[#####Native Session Timeout]]#

After configuring the `DefaultWebSessionManager` instance, session timeout is configured as described in [Session Management: Session Timeout](session-management.html#[[#]]#SessionManagement-sessionTimeout)

<a name="Web-SessionCookie"></a>
#[[#####Session Cookie]]#

The `DefaultWebSessionManager` supports two web-specific configuration properties:

*   `sessionIdCookieEnabled` (a boolean)
*   `sessionIdCookie`, a [Cookie](static/current/apidocs/org/apache/shiro/web/servlet/Cookie.html) instance.

#info('Cookie as a template', 'The <code>sessionIdCookie</code> property is essentially a template - you configure the <code>Cookie</code> instance properties, and this template will be used to set the actual HTTP `Cookie` header at runtime with an appropriate session ID value.')

<a name="Web-SessionCookieConfiguration"></a>
#[[######Session Cookie Configuration]]#

The DefaultWebSessionManager's `sessionIdCookie` default instance is a [`SimpleCookie`](static/current/apidocs/org/apache/shiro/web/servlet/SimpleCookie.html). This simple implementation allows JavaBeans-style property configuration for all of the relevant properties you would want to configure on an http Cookie.

For example, you could set the Cookie domain:

``` ini
[main]
...
securityManager.sessionManager.sessionIdCookie.domain = foo.com
```

See the [SimpleCookie JavaDoc](static/current/apidocs/org/apache/shiro/web/servlet/SimpleCookie.html) for additional properties.

The cookie's default name is `JSESSIONID` in accordance with the servlet specification. Additionally, Shiro's cookie supports the [`HttpOnly`](https://en.wikipedia.org/wiki/HTTP_cookie#HttpOnly_cookie) flag. The `sessionIdCookie` sets `HttpOnly` to `true` by default for extra security.

#info('Note', 'Shiro''s <code>Cookie</code> concept supports the <code>HttpOnly</code> flag even in Servlet 2.4 and 2.5 environments (whereas the Servlet API only supports it natively in 2.6 or later).')

<a name="Web-DisablingtheSessionCookie"></a>
#[[######Disabling the Session Cookie]]#

If you do not want session cookies to be used, you can disable their use by configuring the `sessionIdCookieEnabled` property to false. For example:

**Disabling native session cookies**

``` ini
[main]
...
securityManager.sessionManager.sessionIdCookieEnabled = false
```

<a name="Web-rememberme"></a>
<a name="Web-RememberMeServices"></a>
Remember Me Services
--------------------

Shiro will perform 'rememberMe' services if the `AuthenticationToken` implements the [`org.apache.shiro.authc.RememberMeAuthenticationToken`](static/current/apidocs/org/apache/shiro/authc/RememberMeAuthenticationToken.html) interface. This interface specifies a method:

``` java
boolean isRememberMe();
```

If this method returns `true`, Shiro will remember the end-user's identity across sessions.

#tip('UsernamePasswordToken and RememberMe', 'The frequently-used <code>UsernamePasswordToken</code> already implements the <code>RememberMeAuthenticationToken</code> interface and supports rememberMe logins.')

<a name="Web-ProgrammaticSupport"></a>
#[[###Programmatic Support]]#

To use rememberMe programmatically, you can set the value to `true` on a class that supports this configuration. For example, using the standard `UsernamePasswordToken`:

``` java
UsernamePasswordToken token = new UsernamePasswordToken(username, password);

token.setRememberMe(true);

SecurityUtils.getSubject().login(token);
...
```

<a name="Web-FormbasedLogin"></a>
#[[###Form-based Login]]#

For web applications, the `authc` filter is by default a [`FormAuthenticationFilter`](static/current/apidocs/org/apache/shiro/web/filter/authc/FormAuthenticationFilter.html). This supports reading the 'rememberMe' boolean as a form/request parameter. By default, it expects the request param to be named `rememberMe`. Here is an example shiro.ini config supporting this:

``` ini
[main]
authc.loginUrl = /login.jsp

[urls]

# your login form page here:
login.jsp = authc
```

And in your web form, have a checkbox named 'rememberMe':

``` html
<form ...>

   Username: <input type="text" name="username"/> <br/>
   Password: <input type="password" name="password"/>
    ...
   <input type="checkbox" name="rememberMe" value="true"/>Remember Me?
   ...
</form>
```

By default, the `FormAuthenticationFilter` will look for request parameters named `username`, `password` and `rememberMe`. If these are different than the form field names that you use in your form, you'll want to configure the names on the `FormAuthenticationFilter`. For example, in `shiro.ini`:

``` ini
[main]
...
authc.loginUrl = /whatever.jsp
authc.usernameParam = somethingOtherThanUsername
authc.passwordParam = somethingOtherThanPassword
authc.rememberMeParam = somethingOtherThanRememberMe
...
```

<a name="Web-Cookieconfiguration"></a>
#[[###Cookie configuration]]#

You can configure how the `rememberMe` cookie functions by setting the default {{RememberMeManager}}s various cookie properties. For example, in shiro.ini:

``` ini
[main]
...

securityManager.rememberMeManager.cookie.name = foo
securityManager.rememberMeManager.cookie.maxAge = blah
...
```

See the [`CookieRememberMeManager`](static/current/apidocs/org/apache/shiro/web/mgt/CookieRememberMeManager.html) and the supporting [`SimpleCookie`](static/current/apidocs/src-html/org/apache/shiro/web/servlet/SimpleCookie.html) JavaDoc for configuration properties.

<a name="Web-Custom%7B%7BRememberMeManager%7D%7D"></a>
#[[###Custom `RememberMeManager`]]#

It should be noted that if the default cookie-based `RememberMeManager` implementation does not meet your needs, you can plug in any you like in to the `securityManager` like you would configure any other object reference:

``` ini
[main]
...
rememberMeManager = com.my.impl.RememberMeManager
securityManager.rememberMeManager = $rememberMeManager
```
<a name="Web-taglibrary"></a>
<a name="Web-JSP%2FGSPTagLibrary"></a>
JSP / GSP Tag Library
---------------------

Apache Shiro provides a `Subject`-aware JSP/GSP tag library that allows you to control your JSP, JSTL or GSP page output based on the current Subject's state. This is quite useful for personalizing views based on the identity and authorization state of the current user viewing the web page.

<a name="Web-taglibrary"></a>
<a name="Web-TagLibraryConfiguration"></a>
#[[###Tag Library Configuration]]#

The Tag Library Descriptor (TLD) file is bundled in `shiro-web.jar` in the `META-INF/shiro.tld` file. To use any of the tags, add the following line to the top of your JSP page (or wherever you define page directives):

``` html
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
```

We've used the `shiro` prefix to indicate the shiro tag library namespace, but you can assign whatever name you like.

Now we'll cover each tag and show how it might be used to render a page.

<a name="Web-guesttag"></a>
<a name="Web-The%7B%7Bguest%7D%7Dtag"></a>
#[[### The `guest` tag]]#

The `guest` tag will display its wrapped content only if the current `Subject` is considered a 'guest'. A guest is any `Subject` that does not have an identity. That is, we don't know who the user is because they have not logged in and they are not remembered (from Remember Me services) from a previous site visit.

Example:

``` html
<shiro:guest>
    Hi there!  Please <a href="login.jsp">Login</a> or <a href="signup.jsp">Signup</a> today!
</shiro:guest>
```

The `guest` tag is the logical opposite of the [`user`](#Web-usertag) tag.

<a name="Web-usertag"></a>
<a name="Web-The%7B%7Buser%7D%7Dtag"></a>
#[[###The `user` tag]]#

The `user` tag will display its wrapped content only if the current `Subject` is considered a 'user'. A 'user' in this context is defined as a `Subject` with a known identity, either from a successful authentication or from 'RememberMe' services. Note that this tag is semantically different from the [authenticated](#Web-authenticatedtag) tag, which is more restrictive than this tag.

Example:

``` html
<shiro:user>
    Welcome back John!  Not John? Click <a href="login.jsp">here<a> to login.
</shiro:user>
```

The `user` tag is the logical opposite of the [`guest`](#Web-guesttag) tag.

<a name="Web-authenticatedtag"></a>
<a name="Web-The%7B%7Bauthenticated%7D%7Dtag"></a>
#[[###The `authenticated` tag]]#

Displays body content only if the current user has successfully authenticated _during their current session_. It is more restrictive than the 'user' tag. It is logically opposite to the 'notAuthenticated' tag.

The `authenticated` tag will display its wrapped content only if the current `Subject` has successfully authenticated _during their current session_. It is a more restrictive tag than the [user](#Web-usertag), which is used to guarantee identity in sensitive workflows.

Example:

``` html
<shiro:authenticated>
    <a href="updateAccount.jsp">Update your contact information</a>.
</shiro:authenticated>
```

The `authenticated` tag is the logical opposite of the [`notAuthenticated`](#Web-notauthenticatedtag) tag.

<a name="Web-notauthenticatedtag"></a>
<a name="Web-The%7B%7BnotAuthenticated%7D%7Dtag"></a>
#[[###The `notAuthenticated` tag]]#

The `notAuthenticated` tag will display its wrapped content if the current `Subject` has **NOT** yet successfully authenticated during the current session.

Example:

``` html
<shiro:notAuthenticated>
    Please <a href="login.jsp">login</a> in order to update your credit card information.
</shiro:notAuthenticated>
```

The `notAuthenticated` tag is the logical opposite of the [`authenticated`](#Web-authenticatedtag) tag.

<a name="Web-principaltag"></a>
<a name="Web-The%7B%7Bprincipal%7D%7Dtag"></a>
#[[###The `principal` tag]]#

The `principal` tag will output the Subject's [`principal`](static/current/apidocs/org/apache/shiro/subject/Subject.html#[[#]]#getPrincipal--) (identifying attribute) or a property of that principal.

Without any tag attributes, the tag will render the `toString()` value of the principal. For example (assuming the principal is a String username):

``` html
Hello, <shiro:principal/>, how are you today?
```

This is (mostly) equivalent to the following:

``` html
Hello, <%= SecurityUtils.getSubject().getPrincipal().toString() %>, how are you today?
```

<a name="Web-Typedprincipal"></a>
#[[####Typed principal]]#

The `principal` tag assumes by default that the principal to print is the `subject.getPrincipal()` value. But if you wanted to print a value that is _not_ the primary principal, but another in the Subject's {[principal collection](static/current/apidocs/org/apache/shiro/subject/Subject.html#[[#]]#getPrincipals--), you can acquire that principal by type and print that value instead.

For example, printing the Subject's user ID (and not the username), assuming the ID was in the principal collection:

``` html
User ID: <principal type="java.lang.Integer"/>
```

This is (mostly) equivalent to the following:

``` html
User ID: <%= SecurityUtils.getSubject().getPrincipals().oneByType(Integer.class).toString() %>
```

<a name="Web-Principalproperty"></a>
#[[####Principal property]]#

But what if the principal (either the default primary principal or 'typed' principal above) is a complex object and not a simple string, and you wanted to reference a property on that principal? You can use the `property` attribute to indicate the name of the property to read (must be accessible via a JavaBeans-compatible getter method). For example (assuming the primary principal is a User object):

``` html
Hello, <shiro:principal property="firstName"/>, how are you today?
```

This is (mostly) equivalent to the following:

``` html
Hello, <%= SecurityUtils.getSubject().getPrincipal().getFirstName().toString() %>, how are you today?
```

Or, combined with the type attribute:

``` html
Hello, <shiro:principal type="com.foo.User" property="firstName"/>, how are you today?
```

this is largely equivalent to the following:

``` html
Hello, <%= SecurityUtils.getSubject().getPrincipals().oneByType(com.foo.User.class).getFirstName().toString() %>, how are you today?
```

<a name="Web-hasroletag"></a>
<a name="Web-The%7B%7BhasRole%7D%7Dtag"></a>
#[[###The `hasRole` tag]]#

The `hasRole` tag will display its wrapped content only if the current `Subject` is assigned the specified role.

For example:

``` html
<shiro:hasRole name="administrator">
    <a href="admin.jsp">Administer the system</a>
</shiro:hasRole>
```

The `hasRole` tag is the logical opposite of the [lacksRole](#Web-lacksroletag) tag.

<a name="Web-lacksroletag"></a>
<a name="Web-The%7B%7BlacksRole%7D%7Dtag"></a>
#[[###The `lacksRole` tag]]#

The `lacksRole` tag will display its wrapped content only if the current `Subject` **is NOT** assigned the specified role.

For example:

``` html
<shiro:lacksRole name="administrator">
    Sorry, you are not allowed to administer the system.
</shiro:lacksRole>
```

The `lacksRole` tag is the logical opposite of the [hasRole](#Web-hasroletag) tag.

<a name="Web-hasanyroletag"></a>
<a name="Web-The%7B%7BhasAnyRole%7D%7Dtag"></a>
#[[###The `hasAnyRole` tag]]#

The `hasAnyRole` tag will display its wrapped content if the current `Subject` is assigned _any_ of the specified roles from a comma-delimited list of role names.

For example:

``` html
<shiro:hasAnyRoles name="developer, project manager, administrator">
    You are either a developer, project manager, or administrator.
</shiro:hasAnyRoles>
```

The `hasAnyRole` tag does not currently have a logically opposite tag.

<a name="Web-haspermissiontag"></a>
<a name="Web-The%7B%7BhasPermission%7D%7Dtag"></a>
#[[###The `hasPermission` tag]]#

The `hasPermission` tag will display its wrapped content only if the current `Subject` 'has' (implies) the specified permission. That is, the user has the specified ability.

For example:

``` html
<shiro:hasPermission name="user:create">
    <a href="createUser.jsp">Create a new User</a>
</shiro:hasPermission>
```

The `hasPermission` tag is the logical opposite of the [lacksPermission](#Web-lackspermissiontag) tag.

<a name="Web-lackspermissiontag"></a>
<a name="Web-The%7B%7BlacksPermission%7D%7Dtag"></a>
#[[###The `lacksPermission` tag]]#

The `lacksPermission` tag will display its wrapped content only if the current `Subject` **DOES NOT** have (imply) the specified permission. That is, the user **DOES NOT** have the specified ability.

For example:

``` html
<shiro:lacksPermission name="user:delete">
    Sorry, you are not allowed to delete user accounts.
</shiro:lacksPermission>
```

The `lacksPermission` tag is the logical opposite of the [hasPermission](#Web-haspermissiontag) tag.

#lendAHandDoc()

<input type="hidden" id="ghEditPage" value="web.md.vtl"></input>
